package com.study.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Author tanglingyu
 * @Date: 2021/08/12/ 10:12
 * @Description
 */
@Configuration
public class Mvc3 implements WebMvcConfigurer {

  /**
   * org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration有个@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
   * 意味着系统如果有WebMvcConfigurationSupport的自定义的子类就不会加载WebMvcAutoConfiguration继而不会加载DelegatingWebMvcConfiguration
   * DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport
   * 继而不会加载自定义的有关json解析的配置
   * 采用implements WebMvcConfigurer方式让spring的DelegatingWebMvcConfiguration代理所有implements WebMvcConfigurer的配置
   */
  /**
   * 配置为fastJson
   */
  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    stringHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
    converters.add(0, stringHttpMessageConverter);
    JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue,
        SerializerFeature.WriteDateUseDateFormat);
    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(new MediaType("application", "json", StandardCharsets.UTF_8));
    mediaTypeList.add(new MediaType("application", "*+json", StandardCharsets.UTF_8));
    converter.setFastJsonConfig(fastJsonConfig);
    converter.setSupportedMediaTypes(mediaTypeList);
    converters.add(1, converter);
  }
}
